from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Likes, User, Posts, Comments
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import to_beijing_time

bp = Blueprint('likes', __name__, url_prefix='/likes/')

class AddLike(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_id = data.get('post_id')
        comment_id = data.get('comment_id')
        current_user = get_jwt_identity()
        
        if not post_id and not comment_id:
            return HResult().get_result('error', '参数错误!')

        if post_id is not None and comment_id is not None:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
            
        like = Likes(
            user_id=user.id,
            created_time=to_beijing_time(datetime.utcnow())
        )

        # 检查帖子是否存在
        if post_id:
            post = Posts.query.filter_by(id=post_id, del_flag='1').first()
            if not post:
                return HResult().get_result('error', '帖子不存在!')

            # 检查是否已经点赞
            existing_like = Likes.query.filter_by(
                user_id=user.id,
                post_id=post_id
            ).first()

            # 赋值
            like.post_id = post_id
        else:
            comment = Comments.query.filter_by(id=comment_id).first()
            if not comment:
                return HResult().get_result('error', '评论不存在!')

            # 检查是否已经点赞
            existing_like = Likes.query.filter_by(
                user_id=user.id,
                comment_id=comment_id
            ).first()

            # 赋值
            like.comment_id = comment_id

        if existing_like:
            return HResult().get_result('error', '已经点赞过了!')
            
        db.session.add(like)
        db.session.commit()
        return HResult().get_result('success', '点赞成功!')

class CancelLike(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_id = data.get('post_id')
        comment_id = data.get('comment_id')
        current_user = get_jwt_identity()
        
        if not post_id and not comment_id:
            return HResult().get_result('error', '参数错误!')

        if post_id is not None and comment_id is not None:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()

        if post_id:
            like = Likes.query.filter_by(
                user_id=user.id,
                post_id=post_id
            ).first()
        else:
            like = Likes.query.filter_by(
                user_id=user.id,
                comment_id=comment_id
            ).first()
        
        if like:
            db.session.delete(like)
            db.session.commit()
            return HResult().get_result('success', '取消点赞成功!')
        else:
            return HResult().get_result('error', '未点赞过该帖子或评论!')


class QueryCommentLikes(Resource):
    """查询评论的点赞数量"""
    method_decorators = [jwt_required()]

    def get(self):
        comment_id = request.args.get('comment_id')
        if not comment_id:
            return HResult().get_result('error', '参数错误!')

        likes = Likes.query.filter_by(comment_id=comment_id).all()
        return HResult().get_result('success', data=len(likes))

class QueryPostLikes(Resource):
    """查询帖子的点赞"""
    method_decorators = [jwt_required()]
    
    def get(self):
        post_id = request.args.get('post_id')
        if not post_id:
            return HResult().get_result('error', '参数错误!')
            
        # 检查帖子是否存在且未删除
        post = Posts.query.filter_by(id=post_id, del_flag='1').first()
        if not post:
            return HResult().get_result('error', '帖子不存在!')
            
        likes = Likes.query.filter_by(post_id=post_id).all()
        return HResult().get_result('success', data=[{
            'id': like.id,
            'user': like.user.to_dict(),
            'created_time': like.created_time.strftime('%Y-%m-%d %H:%M:%S')
        } for like in likes])

class QueryUserLikes(Resource):
    """查询用户的喜欢"""
    method_decorators = [jwt_required()]
    
    def get(self):
        # current_user = get_jwt_identity()
        user_id = request.args.get('user_id')
        like_type = request.args.get('like_type')

        if not user_id:
            return HResult().get_result('error', '参数错误!')
        
        likes = Likes.query.filter_by(user_id=user_id)

        # 不同类型的处理
        if like_type == 'post':
            likes = likes.filter_by(post_id=like_type).all()
        elif like_type == 'comment':
            likes = likes.filter_by(comment_id=like_type).all()
        else:
            likes = likes.all()

        return HResult().get_result('success', data=[{
            'id': like.id,
            'post': like.post.to_dict() if like.post else None,
            'comment': like.comment.to_dict() if like.comment else None,
            'created_time': like.created_time.strftime('%Y-%m-%d %H:%M:%S')
        } for like in likes])


class QueryLikeUsers(Resource):
    """查询用户的被点赞"""
    method_decorators = [jwt_required()]

    def get(self):
        user_id = request.args.get('user_id')

        if not user_id:
            return HResult().get_result('error', '参数错误!')

        # 查询被点赞的帖子
        post_likes = (db.session.query(Likes)
                      .join(Posts, Likes.post_id == Posts.id)
                      .filter(Posts.user_id == user_id)
                      .all())

        # 查询被点赞的评论
        comment_likes = (db.session.query(Likes)
                         .join(Comments, Likes.comment_id == Comments.id)
                         .filter(Comments.user_id == user_id)
                         .all())

        # 合并结果
        likes = post_likes + comment_likes

        return HResult().get_result('success', data=[{
            'id': like.id,
            'user': like.user.to_dict(),  # 点赞人信息
            'post': like.post.to_dict() if like.post else None,  # 被点赞的帖子信息
            'comment': like.comment.to_dict() if like.comment else None,  # 被点赞的评论信息
            'created_time': like.created_time.strftime('%Y-%m-%d %H:%M:%S')
        } for like in likes])

api = Api(bp)
api.add_resource(AddLike, '/add/', endpoint='add')
api.add_resource(CancelLike, '/cancel/', endpoint='cancel')
api.add_resource(QueryPostLikes, '/postLikes/', endpoint='post_likes')
api.add_resource(QueryUserLikes, '/userLikes/', endpoint='user_likes')
api.add_resource(QueryCommentLikes, '/commentLikes/', endpoint='comment_likes')
api.add_resource(QueryLikeUsers, '/likeUsers/', endpoint='like_users')